package com.tadpole.music.utils;


import android.content.Context;
import android.util.Log;

import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UpProgressHandler;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.storage.UploadOptions;
import com.tadpole.music.callback.BaseCallback;
import com.tadpole.music.config.Constant;
import com.tadpole.music.config.UrlConfig;
import com.tadpole.music.model.base.DataModel;
import com.tadpole.music.model.base.ModelToken;

import org.json.JSONObject;

import java.util.Calendar;

/**
 * 创建人：zhouliqiang  七牛云上传工具
 * 日  期：2019/2/22  3:22 PM
 * 类说明：QiniuUtil
 */
public class QiniuYunUtil {
    private QiniuUtilI qiniuUtilI;

    private boolean iserr = false;

    private String content;

    public static final String QINIU_DOMAIN = "https://exam.tadpole.qiniu.aiyuechen.com/";//上传七牛的域名


    public QiniuUtilI getQiniuUtilI() {
        return qiniuUtilI;
    }

    public void setQiniuUtilI(QiniuUtilI qiniuUtilI) {
        this.qiniuUtilI = qiniuUtilI;
    }

    /* @comment:upLoadFileToQiNiu  上传图片或者视频至七牛
     * @Params: [path, qiniuUtilI]
     * @return: void
     * @Author: zhouliqiang
     * @Date:   2019/2/22 3:46 PM */
    @SuppressWarnings("unchecked")
    public void upLoadFileToQiNiu(Context context, final int current, final int size, final String path) {
        try {
            final String token = SpUtil.getInstance(context).getString(Constant.YUN_TOKEN, "");
            DataModel.request(ModelToken.GET_HEAD_REQUEST)
                    .token(token)
                    .url(UrlConfig.getYunToken)
                    .execute(new BaseCallback<String>() {
                        @Override
                        public void onSuccess(String data) {
                            try {
                                JSONObject obj = new JSONObject(data);
                                if (obj.getInt("code") == 200) {

                                    Configuration config = new Configuration.Builder()
                                            .chunkSize(256 * 1024)  //分片上传时，每片的大小。 默认 256K
                                            .putThreshhold(512 * 1024)  // 启用分片上传阀值。默认 512K
                                            .connectTimeout(10) // 链接超时。默认 10秒
                                            .responseTimeout(10) // 服务器响应超时。默认 60秒
                                            .build();
                                    final UploadManager uploadManager = new UploadManager(config);
                                    final String key = getNowSystemTime() + path.substring(path.lastIndexOf("."));

                                    uploadManager.put(path, key, obj.getString("data"), new UpCompletionHandler() {
                                        @Override
                                        public void complete(String s, ResponseInfo info, JSONObject jsonObject) {
                                            if (info.isOK()) {
                                                //返回文件的地址
                                                String qiNiuBackPicPath = QINIU_DOMAIN + key;
                                                boolean allok = current == size - 1;
                                                if (qiniuUtilI != null) {
                                                    qiniuUtilI.succeed(allok, current, qiNiuBackPicPath);
                                                }
                                            } else {
                                                String a = info.error;
                                                Log.d("sunyan", a);
                                                if (qiniuUtilI != null) {
                                                    //上传失败
                                                    qiniuUtilI.failure();
                                                }
                                            }
                                        }
                                    }, new UploadOptions(null, null, false, new UpProgressHandler() {
                                        @Override
                                        public void progress(String s, final double percent) {
                                            if (qiniuUtilI != null) {
                                                qiniuUtilI.progress(current, (int) Math.round(percent * 100));
                                            }
                                        }
                                    }, null));
                                }

                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onFailure(String msg) {

                        }

                        @Override
                        public void onComplete() {

                        }

                        @Override
                        public void onBefore() {

                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
            if (qiniuUtilI != null) {
                //上传失败
                qiniuUtilI.failure();
            }
        }
    }


    /* @comment:getNowSystemTime 获取当前系统时间
     * @Params: []
     * @return: java.lang.String
     * @Author: zhouliqiang
     * @Date:   2019/2/22 3:47 PM */
    public static String getNowSystemTime() {
        Calendar calendar = Calendar.getInstance();
        int mYear = calendar.get(Calendar.YEAR); // 获取当前年份
        int mMonth = calendar.get(Calendar.MONTH) + 1;// 获取当前月份
        int mDay = calendar.get(Calendar.DAY_OF_MONTH);// 获取当日期
        int mHour = calendar.get(Calendar.HOUR_OF_DAY);//时
        int mMinute = calendar.get(Calendar.MINUTE);//分
        int mSecond = calendar.get(Calendar.SECOND);//秒
        String nowTime = "" + mYear + "" + mMonth + "" + mDay + "" + mHour + "" + mMinute + "" + mSecond + "" + ((Math.random() * 9 + 1) * 10000);
        return nowTime;
    }

    //回调
    public interface QiniuUtilI {
        void succeed(boolean allok, int current, String qiNiuBackPicPath);

        void failure();

        void progress(int current, int progress);
    }


}
